
<template>
  <el-card>
    <el-row>
      <el-form :inline="true" size="mini" ref="barrageRefForm" :model="barrageQuery" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input v-model="barrageQuery.keyword" placeholder="弹幕内容关键字" ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"   @click="onReset">重置</el-button>
          <el-button type="primary"  @click="handleQuery">查询</el-button>
          <el-button type="danger" @click="batchDel">批量删除</el-button>
          <el-button type="success" class="btn" @click="importExcel" >导入弹幕(Excel)</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </el-card>
  <el-row>
    <el-table
    stripe :data="barrageList"
    style="width: 100%"
    @selection-change="handleSelectionChange"><!--当选择项发生变化时会触发该事件-->
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="编号"/>
      <el-table-column prop="videoTitle" label="所在视频" :show-overflow-tooltip="true"/>
      <el-table-column prop="author.username" label="发布人">
        <template #default="scope">
          <!-- 判断 author.username 是否为空 -->
          <span v-if="scope.row.author && scope.row.author.username">
        {{ scope.row.author.username }}
         </span>
          <span v-else>发布人已被删除</span>
        </template>
      </el-table-column>
      <el-table-column prop="videoTime" label="视频时间">
        <template v-slot="scope">
          {{secondsFormat(scope.row.videoTime)}}
        </template>
      </el-table-column>
      <el-table-column prop="content" label="弹幕内容" :show-overflow-tooltip="true"/>
      <el-table-column prop="color" label="颜色"/>
      <el-table-column prop="fontSize" label="字体大小"/>
      <el-table-column prop="likes" label="点赞数"/>
      <el-table-column prop="status" label="状态">
        <template v-slot="scope">
          <el-switch
              :active-value="0"
              :inactive-value="1"
              v-model="scope.row.status"
              @click="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="releaseTime" label="发布时间"/>
      <el-table-column label="操作">
        <template #default="scope" >
          <el-button type="danger"  @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>

  <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @prev-click="toPage"
      @next-click="toPage"
      @current-change="toPage"/>

  <!--Excel的导入-->
  <el-dialog v-model="importExcelDialogVisible" title="导入线索EXCEL" width="55%" center draggable>
    <el-form  label-width="110px" >
      <el-form-item label="活动备注" >
        <el-upload
            ref="uploadRef"
            :method="post"
            :http-request="uploadFile"
            :auto-upload="false">
          <template #trigger>
            <el-button type="primary">选择Excel文件</el-button>
          </template>
          仅支持后缀名为.xls或.xlsx的文件
          <template #tip>
            <div class="fileTip">
              重要提示：
              <ul>
                <li>上传仅支持后缀名为.xls或.xlsx的文件；</li>
                <li>给定Excel文件的第一行将视为字段名；</li>
                <li>请确认您的文件大小不超过50MB；</li>
                <li>日期值以文本形式保存，必须符合yyyy-MM-dd格式；</li>
                <li>日期时间以文本形式保存，必须符合yyyy-MM-dd HH:mm:ss的格式；</li>
              </ul>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="importExcelDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="submitUpload">导 入</el-button>
      </span>
    </template>
  </el-dialog>


  <!--弹幕没有新增和编辑功能-->

</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import { messageConfirm, messageTip} from "../util/Util.js";

export default {
  name: "BarrageView",
  //注入父级页面提供provide的所有属性（函数，属性，对象）
  data(){
    return{
      //用户列表数据
      barrageList : [{}],
      pageSize : 0,
      total : 0,
      //弹幕的弹窗是否弹出来，true就弹出来，false就不弹出来
      barrageDialogVisible :false,
      //定义弹幕表单对象, 初始值是空
      barrageQuery:{
        keyword:null,
      },
      //弹幕id的数组
      barrageIdArray:[],
      //导入弹幕Excel的弹窗控制
      importExcelDialogVisible:false
    }
  },

  mounted() {
    this.getData(1);
  },

  methods:{
    //把视频总秒格式化成hh:mm:ss的形式
    secondsFormat(seconds){
      //注意小数的精度问题
      let s=parseInt(seconds % 60);
      //不足两位数时给他补0
      s=s<10?'0'+s:s;
      let m=parseInt(seconds /60 %60);
      m=m<10?'0'+m:m;
      let h=parseInt(seconds /60 /60 %24);
      h=h<10?'0'+h:h;
      return `${h}:${m}:${s}`
    },

    //线索导入
    importExcel() {
      //弹个窗
      this.importExcelDialogVisible=true;
    },

    submitUpload() {
      this.$refs.uploadRef.submit();
    },

    //文件上传的函数，element-plus会上传一个param参数，this.$refs.upload.submit()
    //会自动调用httpRequest方法，在里面取得file
   uploadFile(param) {
    console.log(param);
    let fileObj = param.file;
    let formData = new FormData();
    formData.append('file',fileObj)
    doPost("/api/importExcel",formData).then(resp=>{
      if(resp.data.code===200) {
      messageTip('导入成功',"success");
      //清理一下上传的文件
      this.$refs.uploadRef.clearFiles();
      this.$router.go(0);
      }else {
      messageTip("导入失败","error");
      }
    })
  },

    //勾选或者取消勾选时，触发该函数
    handleSelectionChange(selectionDataArray){
      console.log(selectionDataArray);
      selectionDataArray.forEach(data=>{
        let barrageId=data.id;
        this.barrageIdArray.push(barrageId);
      })
    },


    batchDel() {
      if (this.barrageIdArray.length <= 0) {
        //提示一下
        messageTip("请选择要删除的数据", "warning");
        return;
      }
      messageConfirm("您确定要删除这些数据吗？").then(() => { //用户点击“确定”按钮就会触发then函数
        //原来是数组：[1,3,5,6,7,11,15]  --> ids = "1,3,5,6,7,11,15";
        let ids = this.barrageIdArray.join(",");
        doDelete("/api/barrage", {
          ids : ids
        }).then(resp => {
          console.log(resp);
          if (resp.data.code === 200) {
            messageTip("批量删除成功", "success");
            //页面刷新
            this.$router.go(0);
          } else {
            messageTip("批量删除失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => { //用户点击“取消”按钮就会触发catch函数
        messageTip("取消批量删除", "warning");
      })
    },

    //跟据关键字进行查询
    handleQuery() {
      //搜索
      this.getData(1);
    },


    //重置搜索框
    onReset() {
      this.barrageQuery.keyword=null;
      this.$router.go(0);
    },
    //查询弹幕列表数据方法
    getData(current){
      let keyword=this.barrageQuery.keyword
      doGet("/api/barrages",{
        current : current,//当前查询第几页
        keyword: keyword,
      }).then(resp=>{
        console.log(resp)
        if(resp.data.code===200){
          this.barrageList=resp.data.data.list;
          this.pageSize=resp.data.data.pageSize;
          this.total=resp.data.data.total;
        }
      })
    },
    //分页函数(current这个形参是element-plus组件自动传过来的，就是传的当前页)
    toPage(current){
      this.getData(current)
    },
    //删除弹幕
    del (id) {
      messageConfirm("您确定要删除该数据吗？").then(() => { //用户点击“确定”按钮就会触发then函数
        doDelete("/api/barrage/" + id, {}).then(resp => {
          console.log(resp);
          if (resp.data.code === 200) {
            messageTip("删除成功", "success");
            this.$router.go(0);
          } else {
            messageTip("删除失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => { //用户点击“取消”按钮就会触发catch函数
        messageTip("取消删除", "error");
      })
    },
    handleStatusChange(row){
      let statusTip =row.status === 0 ?'启用':'禁用'
      messageConfirm(`是否确认[${statusTip}]这条弹幕?`).then(() => { //用户点击“确定”按钮就会触发then函数
        doPut("/api/barrage/changeStatus",{
          id : row.id,
          status: row.status
        }).then(resp => {
          console.log(resp);
          if (resp.data.code === 200) {
            messageTip("修改成功", "success");
            setTimeout(() => {
            }, 1000); // 延迟 2 秒（与消息提示的显示时长匹配）
          } else {
            messageTip("修改失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => { //用户点击“取消”按钮就会触发catch函数
        //将当前用户的状态值还原到设置前状态
        messageTip("取消修改", "error");
        row.status=row.status===0?1:0
      })
    },
  }
}

</script>

<style scoped>

</style>

